package com.example.voicealarm;

import android.os.Parcel;
import android.os.Parcelable;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

public class Alarm implements Parcelable {
    public long id;
    public Calendar time;
    public boolean[] activeDays = new boolean[7];
    public String ttsText;
    public boolean expired = false;
    public transient int snoozeCount = 0;
    public transient long lastSnoozeTime = 0;

    public Alarm() {
        time = Calendar.getInstance();
        time.add(Calendar.MINUTE, 1); // 默认设置为1分钟后
        expired = false;
        snoozeCount = 0;
        lastSnoozeTime = 0;
    }

    protected Alarm(Parcel in) {
        id = in.readLong();
        time = (Calendar) in.readSerializable();
        activeDays = in.createBooleanArray();
        ttsText = in.readString();
        expired = in.readByte() != 0;
        snoozeCount = in.readInt();
        lastSnoozeTime = in.readLong();
    }

    public static final Creator<Alarm> CREATOR = new Creator<Alarm>() {
        @Override
        public Alarm createFromParcel(Parcel in) {
            return new Alarm(in);
        }

        @Override
        public Alarm[] newArray(int size) {
            return new Alarm[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeSerializable(time);
        dest.writeBooleanArray(activeDays);
        dest.writeString(ttsText);
        dest.writeByte((byte) (expired ? 1 : 0));
        dest.writeInt(snoozeCount);
        dest.writeLong(lastSnoozeTime);
    }

    public void setTime(Calendar time) {
        this.time = (Calendar) time.clone();
        this.expired = false;
        adjustTimeIfNeeded();
    }

    private void adjustTimeIfNeeded() {
        if (!isRepeating()) {
            Calendar now = Calendar.getInstance();
            Calendar adjustedTime = (Calendar) time.clone();
            adjustedTime.set(Calendar.YEAR, now.get(Calendar.YEAR));
            adjustedTime.set(Calendar.MONTH, now.get(Calendar.MONTH));
            adjustedTime.set(Calendar.DAY_OF_MONTH, now.get(Calendar.DAY_OF_MONTH));
            
            if (adjustedTime.before(now)) {
                adjustedTime.add(Calendar.DAY_OF_YEAR, 1);
                time = adjustedTime;
            }
        }
    }

    public boolean isRepeating() {
        for (boolean active : activeDays) {
            if (active) return true;
        }
        return false;
    }

    public Calendar getNextAlarmTime() {
        Calendar calendar = (Calendar) time.clone();
        Calendar now = Calendar.getInstance();
        
        calendar.set(Calendar.YEAR, now.get(Calendar.YEAR));
        calendar.set(Calendar.MONTH, now.get(Calendar.MONTH));
        calendar.set(Calendar.DAY_OF_MONTH, now.get(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        
        if (isRepeating()) {
            // For repeating alarms, find the next active day
            int todayDayOfWeek = now.get(Calendar.DAY_OF_WEEK) - 1; // 0=Sunday
            int daysToAdd = 0;
            
            // Check remaining days in this week
            for (int i = 0; i < 7; i++) {
                int dayToCheck = (todayDayOfWeek + i) % 7;
                if (activeDays[dayToCheck] && (i > 0 || calendar.after(now))) {
                    daysToAdd = i;
                    break;
                }
            }
            
            // If no days found in this week, check next week
            if (daysToAdd == 0) {
                for (int i = 0; i < todayDayOfWeek; i++) {
                    if (activeDays[i]) {
                        daysToAdd = i + (7 - todayDayOfWeek);
                        break;
                    }
                }
            }
            
            calendar.add(Calendar.DAY_OF_YEAR, daysToAdd);
        } else if (calendar.before(now)) {
            // For one-time alarms, if time has passed today, schedule for tomorrow
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }
        
        return calendar;
    }

    public String getTimeUntilNextAlarm() {
        if (isExpired()) {
            return "闹钟已过期";
        }
        
        Calendar nextAlarm = getNextAlarmTime();
        Calendar now = Calendar.getInstance();
        
        long diffInMillis = nextAlarm.getTimeInMillis() - now.getTimeInMillis();
        long hours = TimeUnit.MILLISECONDS.toHours(diffInMillis);
        long minutes = TimeUnit.MILLISECONDS.toMinutes(diffInMillis) % 60;
        
        if (hours > 24) {
            long days = hours / 24;
            return days + "天后响铃";
        } else if (hours > 0) {
            return String.format("%d小时%d分钟后响铃", hours, minutes);
        } else {
            return String.format("%d分钟后响铃", minutes);
        }
    }

    public boolean isExpired() {
        if (expired) {
            return true;
        }
        
        Calendar nextAlarm = getNextAlarmTime();
        boolean shouldBeExpired = nextAlarm.before(Calendar.getInstance());
        
        if (shouldBeExpired) {
            expired = true;
        }
        
        return expired;
    }

    public String getSnoozeStatus() {
        if (snoozeCount > 0 && lastSnoozeTime > 0) {
            long now = System.currentTimeMillis();
            long diffSeconds = (now - lastSnoozeTime) / 1000;
            if (diffSeconds < 300) {  // 5分钟 = 300秒
                int remainingMinutes = (int) Math.ceil((300 - diffSeconds) / 60.0);
                return String.format("已响%d次. %d分钟后再响", snoozeCount, remainingMinutes);
            }
        }
        return null;
    }
}